using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows;
using NUnit.Framework;
using Rhino.Mocks;
using SCSFContrib.CompositeUI.WPF;

namespace SCSFContrib.CompositeUI.WPF.UnitTest
{
	[TestFixture]
	public sealed class WindowShellApplicationTest : UnitTest
	{
		private WindowShellApplication<TestableRootWorkItem, Window> _windowShellApplication;

		protected override void SetUpCore()
		{
			base.SetUpCore();
			_windowShellApplication = Mocks.PartialMock<WindowShellApplication<TestableRootWorkItem, Window>>();
			Mocks.ReplayAll();
		}

		[Test]
		[ExpectedException(typeof(InvalidOperationException), "No application has been created.")]
		public void Start_ShouldThrowIfNoApplicationHasBeenCreated()
		{
			ExecuteInSeparateAppDomain("Start_ShouldThrowIfNoApplicationHasBeenCreated_DoWork");
		}

		private void Start_ShouldThrowIfNoApplicationHasBeenCreated_DoWork()
		{
			_windowShellApplication = Mocks.PartialMock<WindowShellApplication<TestableRootWorkItem, Window>>();
			Mocks.ReplayAll();
			_windowShellApplication.Run();
		}

		[Test]
		public void Start_ShouldStartApplication()
		{
			ManualResetEvent applicationLoaded = new ManualResetEvent(false);
			SynchronizationContext synchronizationContext = null;

			//start up application on a separate thread
			Thread thread = CreateSTAThread(delegate
			{
				Application application = new Application();
				application.Startup += delegate
				{
					synchronizationContext = SynchronizationContext.Current;
					applicationLoaded.Set();
				};

				_windowShellApplication.Run();
			});

			thread.Start();
			applicationLoaded.WaitOne();

			synchronizationContext.Send(delegate
			{
				Assert.IsNotNull(Application.Current.MainWindow);
				Application.Current.Shutdown();
			}, null);
		}
	}
}
